package br.com.advance.automacao.dao.impl;

import java.io.Serializable;
import java.util.Date;
import java.util.List;

import javax.persistence.Query;
import javax.persistence.TemporalType;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Repository;

import br.com.advance.automacao.dao.EventoDao;
import br.com.advance.automacao.dto.ContabilizacaoEventos;
import br.com.advance.automacao.generic.dao.impl.GenericDaoImpl;
import br.com.advance.automacao.model.Evento;

@Repository("eventoDao")
public class EventoDaoImpl extends GenericDaoImpl<Evento, Serializable> implements EventoDao {

	private static final Logger logger = Logger.getLogger(EventoDaoImpl.class);
	
	@SuppressWarnings("unchecked")
	@Override
	public List<Evento> buscarPorFiltro(Long idCLP, Long idTurno, Date dataTurno) {
		Query query = entityManager.createNamedQuery(Evento.BUSCAR_EVENTOS_POR_FILTRO);
		query.setParameter("idCLP", idCLP);
		query.setParameter("idTurno", idTurno);
		query.setParameter("data", dataTurno, TemporalType.DATE);

		return query.getResultList();
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public List<ContabilizacaoEventos> buscarContabilizadoPorFiltro(Long idCLP, Long idTurno, Date dataTurno) {
		StringBuilder jpql = new StringBuilder(" select new br.com.advance.automacao.dto.ContabilizacaoEventos( ");
		jpql.append(" er.codigo, er.descricao, COUNT(er.codigo), SUM(e.tempo) ");
		jpql.append(" ) ");
		jpql.append(" FROM Evento e join e.erro er ");
		jpql.append(" WHERE ");
		jpql.append(" e.clp.id = :idCLP AND e.turno.id = :idTurno AND e.data = :data ");
		jpql.append(" GROUP BY er.codigo, er.descricao ");
		jpql.append(" ORDER BY SUM(e.tempo) ");
		
		Query query = entityManager.createQuery(jpql.toString());
		query.setParameter("idCLP", idCLP);
		query.setParameter("idTurno", idTurno);
		query.setParameter("data", dataTurno, TemporalType.DATE);

		return query.getResultList();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Date> buscarDataEventosPorClp(Long idCLP) {
		Query query = entityManager.createNamedQuery(Evento.BUSCAR_DATA_EVENTOS_POR_CLP);
		query.setParameter("idCLP", idCLP);
		return query.getResultList();
	}
	
	@Override
	public void deletarEventosPorClpDataTurno(Long idTurno, Date dataEvento, Long idCLP) {
		Query query = entityManager.createNamedQuery(Evento.DELETAR_EVENTOS_POR_CLP_DATA_TURNO);
		query.setParameter("idCLP", idCLP);
		query.setParameter("idTurno", idTurno);
		query.setParameter("dataEvento", dataEvento, TemporalType.DATE);
		int qtd = query.executeUpdate();
		if (qtd > 0) {
			logger.warn("Foram deletados "+qtd+" registros do CLP ID: "+ idCLP +" ID Turno: " + idTurno + " Data: " + dataEvento);
		}
	}
}
